const jwt = require('jsonwebtoken')
const config = require('../config')

const secret = config.jwt.secret

function createToken(data) {
  const token = 'Bearer ' + jwt.sign(
    {
      data
    },
    secret, {
    expiresIn: '30d' // 过期时间 30天
  })

  return token
}

function verifyToken(token) {
  const tokenSplit = token.split(" ")
  if (tokenSplit[0] !== "Bearer" && tokenSplit.length !== 2) {
    return null
  }

  let auth = null
  try {
    auth = jwt.verify(tokenSplit[1], secret)
  } catch (error) {
    auth = null
  }
  return auth
}

function getuid(ctx) {
  return ctx.state.user?.data?.user?._id || null
}

module.exports = {
  createToken,
  verifyToken,
  getuid
}